package tungsten.base.thread;

import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Lv on 2016/6/24.
 */
public class ThreadPool
{
    private static Logger logger = Logger.getLogger(ThreadPool.class);

    private static Map<String,ExecutorService> threads = new HashMap<>();

    public static ScheduledThreadPoolExecutor scheduleThreadPool(String name, int corePoolSize)
    {
        return new ScheduledThreadPoolExecutor(corePoolSize,new DefaultThreadFactory(name));
    }

    public static void initThread(String name,int corePoolSize,int maximumPoolSize, long keepAliveTime, TimeUnit unit,BlockingQueue<Runnable> workQueue)
    {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
                keepAliveTime, unit,
                workQueue,new DefaultThreadFactory(name));

        threads.put(name,executor);
    }

    public static Future<?> submit(String name, Runnable runnable)
    {
        ExecutorService service = threads.get(name);
        if(service == null)
        {
            logger.error("no thread pool named : " + name);
            return null;
        }
        return service.submit(runnable);
    }

    private static class DefaultThreadFactory implements ThreadFactory
    {
        private ThreadGroup group;
        private AtomicInteger index;
        private String name;

        public DefaultThreadFactory(String name)
        {
            this.name = name;
            this.group = new ThreadGroup(name);
            this.index = new AtomicInteger(0);
        }
        @Override
        public Thread newThread(Runnable r)
        {
            return new Thread(group,r,name + index.getAndIncrement());
        }
    }
}